import type { Song } from './api';
import { addHistory } from './storage';

let audio: WechatMiniprogram.InnerAudioContext | null = null;

export const getAudio = () => {
  if (!audio) {
    audio = wx.createInnerAudioContext();
    audio.obeyMuteSwitch = false;
    audio.autoplay = false;
  }
  return audio;
}

let currentSong: Song | null = null;

export const playSong = (song: Song, onEnded?: () => void) => {
  const a = getAudio();
  a.src = song.url;
  a.play();
  currentSong = song;
  addHistory(song);
  if (onEnded) {
    a.offEnded();
    a.onEnded(onEnded);
  }
}

export const pause = () => getAudio().pause();
export const stop = () => getAudio().stop();

export const setSeek = (position: number) => {
  const a = getAudio();
  a.seek(position);
}

export const getState = () => {
  const a = getAudio();
  return { 
    src: a.src, 
    paused: a.paused || true, 
    startTime: a.startTime, 
    currentTime: a.currentTime || 0, 
    duration: a.duration || 0, 
    volume: 1,
    currentSong: currentSong
  };
}